<?php

require_once('Facility.php');

class Facilities {
	protected $index = array();
	protected $btypes = array();
	protected $columns;

	function __construct($file) {	// array of tab-separated values
		$facilities = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
		// $columns store the file format
		$this->columns = preg_split('/\t/', array_shift($facilities));
		foreach ($facilities as $tsv) {
			$entry = new Facility($tsv, $this->columns);
			$this->index[$entry->ID] = $entry;
			if (!empty($entry->Buildingtype)) {
				$this->btypes[$entry->Buildingtype][$entry->ID] =& $this->index[$entry->ID];
			} 
		}
	}

	function get_columns() {
		return implode("\t", $this->columns);
	}
	function get_id($id) {
		$id = (int)$id;
		return isset($this->index[$id]) ? $this->index[$id]: null;
	}

	function get_all() {
		return $this->index;
	}

	function get_buildingtypes() {
		$names = array_keys($this->btypes);
		if (!sort($names)) {
			throw new Exception('Failed to sort on Buildingtype');
		}
		return $names;
	}

	function count_buildingtype($btype) {
		return count($this->btypes[$btype]);
	}
	function facility_list_html(array $btypes=array()) {
		$html = array();
		foreach ($btypes as $btype) {
			$selected = $this->filter_buildingtypes($btypes);
			if (empty($selected)) {
				continue;
			}
			$html[] = '<ul class="facility-list">';
			foreach($selected as $facility) {
				$html[] = sprintf('<li>%s</li>', $facility->name_popup_link());
			}
			$html[] = '</ul>';
		}
		return implode("\n", $html);
	}
	function filter_buildingtypes(array $btypes=array()) {
/*		if (empty($btypes)) {
			return $this->index;
		}*/
		$selected = array();
		foreach ($btypes as $btype) {
			$selected = array_merge($selected, $this->btypes[$btype]);
		}
		return $selected;
	}

}
